document.addEventListener('DOMContentLoaded', () => {
  // 获取DOM元素
  const tabs = document.querySelectorAll('.tab');
  const resourceLists = document.querySelectorAll('.resource-list');

  // 选项卡切换逻辑
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      // 移除所有选项卡和资源列表的active类
      tabs.forEach(t => t.classList.remove('active'));
      resourceLists.forEach(list => list.classList.remove('active'));

      // 添加当前选项卡和对应资源列表的active类
      tab.classList.add('active');
      const type = tab.dataset.type;
      document.getElementById(`${type}-list`).classList.add('active');
    });
  });

  // 向content script发送消息获取资源
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, { action: 'getResources' }, (response) => {
      if (response) {
        displayResources('images-list', response.images);
        displayResources('videos-list', response.videos);
        displayResources('audios-list', response.audios);
      }
    });
  });

  // 显示资源列表
  function displayResources(listId, resources) {
    const list = document.getElementById(listId);
    if (!resources || resources.length === 0) {
      list.innerHTML = '<div class="no-resources">暂无资源</div>';
      return;
    }

    list.innerHTML = resources.map((resource, index) => {
      const preview = listId === 'images-list' ?
        `<img src="${resource.url}" alt="图片 ${index + 1}">` :
        listId === 'videos-list' ?
          `<video src="${resource.url}" controls></video>` :
          `<audio src="${resource.url}" controls></audio>`;

      return `
        <div class="resource-item">
          ${preview}
          <button class="download-btn" data-url="${resource.url}">下载</button>
        </div>
      `;
    }).join('');

    // 添加下载按钮事件监听
    list.querySelectorAll('.download-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        const url = btn.dataset.url;
        chrome.downloads.download({
          url: url,
          filename: getFilenameFromUrl(url)
        });
      });
    });
  }

  // 从URL中获取文件名
  function getFilenameFromUrl(url) {
    const urlObj = new URL(url);
    const pathname = urlObj.pathname;
    const filename = pathname.substring(pathname.lastIndexOf('/') + 1);
    return filename || 'download';
  }

  // 添加右键菜单下载所有资源的事件监听
  document.addEventListener('contextmenu', (event) => {
    const list = event.target.closest('.resource-list');
    if (list && list.classList.contains('active')) {
      event.preventDefault();
      const buttons = list.querySelectorAll('.download-btn');
      buttons.forEach(btn => {
        const url = btn.dataset.url;
        chrome.downloads.download({
          url: url,
          filename: getFilenameFromUrl(url)
        });
      });
    }
  });
});